package erfgame.core.world.terrain.file;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import erfgame.core.world.World;

public class SurfaceSerializer implements Serializer<int[][][]> {

	private World world;
	
	public SurfaceSerializer( World world ) {
		this.world = world;
	}

	public int[][][] retrieveObject(InputStream ins, int[][][] into)
			throws Exception {
		int w = world.getBlockWidth();
		int h = world.getBlockHeight();
		if( into == null ) {
			into = new int[ w ][ h ][];
		}
		DataInputStream dis = new DataInputStream( ins );
		for( int x=w; x>0; ) {
			x--;
			int[][] intoX = into[x]; 
			for( int y=h; y>0; ) {
				y--;
				int length = dis.read();
				int[] intoXY = new int[length];
				for( int i=length; i>0; ) {
					i--;
					intoXY[i] = dis.readShort();
				}
				intoX[y] = intoXY; 
			}
		}
		return into;
	}

	public void storeObject(OutputStream outs, int[][][] object)
			throws Exception {
		DataOutputStream dos = new DataOutputStream( outs );
		int w = world.getBlockWidth();
		int h = world.getBlockHeight();
		for( int x=w; x>0; ) {
			x--;
			int[][] objectX = object[x];
			for( int y=h; y>0; ) {
				y--;
				int[] objectXY = objectX[y];
				dos.write( objectXY.length );
				for( int i=objectXY.length; i>0; ) {
					i--;
					int surface = objectXY[i];
					dos.writeShort( surface );
				}
			}
		}
		dos.flush();
	}
}
